/*
 * Copyright 2020-2030 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.gitee.minimalismstyle.fresh.common.dubbo.filter

import com.alibaba.dubbo.common.Constants
import com.alibaba.dubbo.rpc.Filter
import com.alibaba.dubbo.rpc.Invocation
import com.alibaba.dubbo.rpc.Invoker
import com.alibaba.dubbo.rpc.Result
import com.fasterxml.jackson.databind.ObjectMapper
import com.gitee.minimalismstyle.fresh.common.security.util.SecurityContextUtils
import com.gitee.minimalismstyle.fresh.common.core.const.CacheConst
import com.gitee.minimalismstyle.fresh.common.security.domain.FreshUserDetails
import org.apache.dubbo.common.extension.Activate
import org.apache.dubbo.rpc.RpcContext

/**
 * 消费者过滤器
 * @author maoxiaodong
 */
@Activate(group = [Constants.CONSUMER])
class ConsumerContextFilter: Filter {

    override fun invoke(invoker: Invoker<*>, invocation: Invocation): Result {
        val user = SecurityContextUtils.user()
        if(user != null){
            val om = ObjectMapper()
            val userString = om.writeValueAsString(FreshUserDetails(
                    id = user.id,
                    tenantId = user.tenantId,
                    username = user.username
            ))
            // 将当前用户信息传过去
            RpcContext.getContext().setAttachment(CacheConst.USER_INFO_KEY, userString)
        }

        return invoker.invoke(invocation)
    }
}